package com.elinkway.infinitemovies.utils;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.KeyguardManager;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.pm.Signature;
import android.content.res.AssetManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.webkit.WebView;

import com.elinkway.infinitemovies.application.MoviesApplication;
import com.elinkway.infinitemovies.bean.App;
import com.elinkway.infinitemovies.bean.Cde;
import com.elinkway.infinitemovies.bean.JumpData;
import com.elinkway.infinitemovies.bean.PlatForm;
import com.elinkway.infinitemovies.bean.PostCloudErrorBean;
import com.elinkway.infinitemovies.bean.Resource;
import com.elinkway.infinitemovies.bean.User;
import com.elinkway.infinitemovies.dao.PreferencesManager;
import com.elinkway.infinitemovies.ui.activity.commonwebview.CommonWebViewActivity;
import com.le123.ysdq.R;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.URL;
import java.net.URLConnection;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.Locale;
import java.util.Random;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class Utils {
    public static String TAG = "newStream"; //新流播放TAG
    public static String DOWN_TAG = "newStreamDown"; //新流下载TAG
    public static String ACTION_TYPE = "actionType";
    public final static String DOWNLOAD_FAIL_CHANGE_M3U8 = "downloadFailChangeM3u8";

    public static String publicIpAddress = "";

    public static String MAIN_ACTIVITY = "0";
    public static String TOPIC_ACTIVITY = "1";
    public static String VIDEO_DETAIL_ACTIVITY = "2";
    public static String TOPIC_DETAIL_ACTIVITY = "3";
    public static String RANK_DETAIL_ACTIVITY = "4";
    public static String PLAY_ACTIVITY = "5";
    public static String WEB_ACTIVITY = "6";
    public static String SHORT_VIDEO = "7";

    public static int STREAM_PLAY = 0;
    public static int STREAM_DOWN = 1;

    public static final int AD_DATA_WAIT = 666;

    // Ad_Type
    public static final String NO_AD = "1";
    public static final String SERVER_AD = "2";
    public static final String GOOGLE_AD = "3";
    public static final String BAIDU_AD = "5";
    public static final String BAIDU_INTER_AD = "6";
    public static final String GDT_AD = "7";
    public static final String GDT_SPLASH_AD = "8";
    public static final String GDT_AD_SHOW_ONE = "0";
    public static final String GDT_AD_SHOW_TWO = "1";
    public static final String HZ_AD = "10";
    public static final String YZ_AD = "9";
    public static final String XF_AD = "11";
    public static final String TT_AD = "12";

    // wuxinrong added begin
    public static final String VMEDIA_AD = "4";
    // wuxinrong added end

    // lihui3 网站上获取聚效广告标志位ID
    public static final boolean VMEDIA_AD_IS_TEST = false;//是否测试 true-测试 false-正式
    public static final String VMEDIA_AD_ID_RECOMMEND_MIDDLE = "uFa6PTn96w";//推荐中间
    public static final String VMEDIA_AD_ID_RECOMMEND_BOTTOM = "uFa6PTn96w";//推荐底部悬浮
    public static final String VMEDIA_AD_ID_MORE_1ST = "aFuQkede6Q";//更多一屏
    public static final String VMEDIA_AD_ID_CHANNEL_BOTTOM = "a5k6uJowlN";//频道底部
    public static final String VMEDIA_AD_ID_TOPIC_TOP = "F5uba99H6E";//专题顶部
    public static final String VMEDIA_AD_ID_RANK_BOTTOM = "55FGPJJR7b";//排行底部
    public static final String VMEDIA_AD_ID_VIDEO_DETAIL_MIDDLE = "5ukbuJeRR7";//视频详情中间
    // VMEDIA 广告尺寸
    public static final int VMEDIA_AD_WIDTH = 640;
    public static final int VMEDIA_AD_HEIGHT = 100;

    public static final String END = "1";

    public static final String YINGSHIDAQUAN_APPID = "700";

    public static final String KUAIYINGSHI_APPID = "";

    public static final String FROM_APP = "appstore";

    public static final String FROM = "from";
    public static final String IS_INNER_WEBVIEW_DOWNLOAD = "is_inner_webview_download";


    public static String cpu_result = "";

    public static String todayTime = "";

    public static String HEADER = "<!doctype html>\n" +
            "<html><head>\n" +
            "    <style type='text/css'>\n" +
            "        html { font-family:Helvetica; color:#222; }\n" +
            "        h1 { color:steelblue; font-size:24px; margin-top:24px; }\n" +
            "        button { margin:0 3px 10px; font-size:12px; }\n" +
            "        .logLine { border-bottom:1px solid #ccc; padding:4px 2px; font-family:courier; font-size:11px; }\n" +
            "        </style>\n" +
            "</head><body>\n" +
            "    <h1>WebViewJavascriptBridge Demo</h1>\n" +
            "    <script>";

    public static String FOOTER = "</script>\n" +
            "</body></html>\n";

    /**
     * android4.4后，SD 卡下载的系统目录
     */
    public static String getDownLoadFolder() {
        StringBuilder sb = new StringBuilder();
        sb.append("Android/data/")
                .append(MoviesApplication.getInstance().getPackageName())
                .append("/files/Movies").toString();
        return sb.toString();
    }

    /**
     * SD 卡路径
     */
    public final static String SDCARD_PATH = Environment
            .getExternalStorageDirectory().getAbsolutePath();
    /**
     * 创建快看文件夹路径
     */
    public final static String SAVE_FILE_PATH_DIRECTORY = SDCARD_PATH + "/"
            + getDownLoadFolder();
    /**
     * sd卡容量广播
     */
    public static final String SDCARD_NOSPACE_ACTION = "com.kuaikan.SDCARDNOSPACE";

    /**
     * 微信分享ID
     */
    // wx9c596e90ce61174a
    // weixin wxd930ea5d5a258f4f
    public static final String WEIXIN_APP_ID = "wxd930ea5d5a258f4f";

    public static final String YINGSHIDAQUAN = "yingshidaquan.apk";
    /**
     * 微信分享秘钥
     */
    public static final String WEIXIN_APPSECRET = "9b634387cdd1f0a27e19ae47b916666e";

    public static final String GRID_LAND_PIC = "34";

    public static final String GRID_VERTICAL_PIC = "43";

    /**
     * 跳转至频道页面需要的key值
     */
    public static final String CHANNEL_DTAT = "channeldata";

    public static final String AD_INFO = "ad_info";
    public static final String AD_POS = "ad_pos";

    public static final String LINK = "link";

    public static final String PLAY_DATA = "play_data";

    public static final String ALBUM_DATA = "album_data";

    public static final String THEME_DATA = "theme_data";

    public static final String PLAY_3G_NET = "3G_play";

    public static final String VIDEO_TITLE = "title";

    public static String ALBUM = "album";

    public static String THEME = "theme";

    public static final String ACTIVITY = "activity";

    public static final String LIVE = "live";

    public static final String DRAWABLE = "drawable";

    /**
     * 存放二维码的路径
     */
    private final static String ALBUM_PATH = Environment
            .getExternalStorageDirectory() + "/Infinitemovies/";

    public static String SHARE_QRCODE = "shareqrcode";

    public static String QRCODE_SAVE_PATH = ALBUM_PATH + SHARE_QRCODE;

    /**
     * 播放器进图条发生变化
     */
    public static final int PROGRESS_CHANGE = 0;

    public static final int TIME_REPORT = 180;

    public static final int GET_JS_RESULT = 300;

    public static final int TIME_REFRESH = 310;

    public static final int TOP_CONTROL = 311;

    public static final int AD_SECOND = 411;
    /**
     * 控制栏消失
     */
    public static final int DISSMISS_MEDIACONTROLLER = PROGRESS_CHANGE + 1;

    public static final int JUDGE_BUFFER = DISSMISS_MEDIACONTROLLER + 1;

    /**
     * 消除手势操作时的弹窗
     */
    public static final int VIDEO_DISMISS_GESTURE_POPUPWINDOW = JUDGE_BUFFER + 1;
    /**
     * 显示清晰度提示
     */
    public static final int VIDEO_SHOW_CHANGE_CLARITY = VIDEO_DISMISS_GESTURE_POPUPWINDOW + 1;

    public static final int DISSMISS_VIDEOSELECT_LIST = VIDEO_SHOW_CHANGE_CLARITY + 1;

    public static final int DISSMISS_ALL_OVERLAYER = DISSMISS_VIDEOSELECT_LIST + 1;

    /**
     * 消除手势弹窗的时间
     */
    public static final int VIDEO_DISMISS_GESTURE_POPUPWINDOW_TIME = 500;
    /**
     * 控制栏消失的时间
     */
    public static final int MEDIA_CONTROLLER_DISMISS_TIME = 5000;

    public static final int EXECUTE_JS_TIME = 300;

    /**
     * 切换清晰度后，10秒钟还没有缓冲完，显示控制栏提示切换清晰度
     */
    public static final int MEDIA_CONTROLLER_SHOW_TIME = 10000;

    /**
     * 判断视频缓冲的延迟时间
     */
    public static final long JUDGE_BUFFER_DELAY_TIME = 3000;

    public static final long CHECK_UTP_SEVER_TIME = 1000;

    public final static int DEVICE_WIDTH_240X320 = 240;

    public final static int DEVICE_WIDTH_320X480 = 320;

    public final static int DEVICE_WIDTH_480X800 = 480;

    public final static int DEVICE_WIDTH_640X960 = 640;

    public final static int DEVICE_WIDTH_720X1280 = 720;

    public final static int DEVICE_WIDTH_800X1280 = 800;

    public final static int SDCARD_MINSIZE = 100;

    public static final int DISSMISS_LOADING_VIEW = 1024;

    public static final byte[] AES_KEY = {49, 50, 51, 52, 53, 54, 55, 56, 57,
            48, 49, 50, 51, 52, 53, 54};

    public static final String CLOUDPARSERMAINURL = "aHR0cDovL2JwbGF5LmczcHJveHkubGVjbG91ZC5jb20vdm9kL3YyL01UWTVMelV2T0RRdmJHVjBkaTExZEhNdk1qQXZkbVZ5WHpBd1h6SXlMVEV3TVRrNE1ERTRNemt0WVhaakxUUXhPVEEwTmkxaFlXTXRNekl3TURBdE1UUXhOVFkwTUMwNE1UTTNNVGd3T1MxbFpHTTVNbU0zTm1Vek1XTXlPRGRtTVRobFlURmxZVE5qTXprMlpEaGlOeTB4TkRVek1EZzNOell4TmpVNUxtMXdOQT09P2I9NDU5Jm1tc2lkPTQyNDQ4NDcyJnRtPTE0NTMyODU4MTIma2V5PTQzN2UyNWU0NmUwYjRlZWVkZmRkMDA2MGIyYzEyNTAwJnBsYXRpZD0xNCZzcGxhdGlkPTE0MDgmcGxheWlkPTAmdHNzPWlvcyZ2dHlwZT0xMyZjdmlkPTM5MjIzODQ4MTI5NiZwYXlmZj0wJnBpcD1lZDY1N2IwNzU5ZDM0N2RlNWUwOGM2NDNhYzVjNWNlOA==";

    /**
     * 获取手机型号 zhangshuo 2015年1月29日 下午4:33:40
     */
    public static String getDeviceMode() {
        try {
            return android.os.Build.MODEL;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 获取操作系统版本 zhangshuo 2015年1月29日 下午4:34:16
     */
    public static String getDeviceVersion() {
        try {
            return android.os.Build.VERSION.RELEASE;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public static int getAPILevel() {
        try {
            return android.os.Build.VERSION.SDK_INT;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 获取手机当前是否锁屏
     *
     * @return zhangshuo 2014年4月29日 下午5:23:19
     */
    public static boolean getScreenLockStatus() {
        Context context = MoviesApplication.getInstance();
        if (null == context) {
            return true;
        }

        try {
            KeyguardManager mkeyguardManager = (KeyguardManager) context
                    .getSystemService("keyguard");
            return (null != mkeyguardManager && mkeyguardManager
                    .inKeyguardRestrictedInputMode());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    public static int getDifferentScreenOffsetX(Context ctx) {
        if (null == ctx) {
            return 0;
        }
        int deviceWidthPixels = getHeightPixels(ctx);
        if (deviceWidthPixels > 0 && deviceWidthPixels <= DEVICE_WIDTH_320X480) {
            return -4;
        } else if (deviceWidthPixels > DEVICE_WIDTH_320X480
                && deviceWidthPixels <= DEVICE_WIDTH_480X800) {
            return 25;
        } else if (deviceWidthPixels > DEVICE_WIDTH_480X800
                && deviceWidthPixels <= DEVICE_WIDTH_720X1280) {
            return 38;
        } else if (deviceWidthPixels > DEVICE_WIDTH_720X1280
                && deviceWidthPixels <= DEVICE_WIDTH_800X1280) {
            return 34;
        } else {
            return 37;
        }
    }

    public static int convertDipOrPx(int dip) {
        Context context = MoviesApplication.getInstance()
                .getApplicationContext();
        float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dip * scale + 0.5f * (dip >= 0 ? 1 : -1));
    }

    public static int getHeightPixels(Context context) {
        DisplayMetrics dm = new DisplayMetrics();
        ((Activity) context).getWindowManager().getDefaultDisplay()
                .getMetrics(dm);
        return dm.heightPixels;
    }

    public static int getWidthPixels(Context context) {
        if (null == context || !(context instanceof Activity)) {
            return 480;
        }
        DisplayMetrics dm = new DisplayMetrics();
        ((Activity) context).getWindowManager().getDefaultDisplay()
                .getMetrics(dm);
        return dm.widthPixels;
    }

    public static byte[] bmpToByteArray(final Bitmap bmp,
                                        final boolean needRecycle) {
        int i;
        int j;
        if (bmp.getHeight() > bmp.getWidth()) {
            i = bmp.getWidth();
            j = bmp.getWidth();
        } else {
            i = bmp.getHeight();
            j = bmp.getHeight();
        }

        Bitmap localBitmap = Bitmap.createBitmap(i, j, Bitmap.Config.RGB_565);
        Canvas localCanvas = new Canvas(localBitmap);

        while (true) {
            localCanvas.drawBitmap(bmp, new Rect(0, 0, i, j), new Rect(0, 0, i,
                    j), null);
            if (needRecycle)
                bmp.recycle();
            ByteArrayOutputStream localByteArrayOutputStream = new ByteArrayOutputStream();
            localBitmap.compress(Bitmap.CompressFormat.JPEG, 100,
                    localByteArrayOutputStream);
            localBitmap.recycle();
            byte[] arrayOfByte = localByteArrayOutputStream.toByteArray();
            try {
                localByteArrayOutputStream.close();
                return arrayOfByte;
            } catch (Exception e) {
                // F.out(e);
            }
            i = bmp.getHeight();
            j = bmp.getHeight();
        }
    }

    public static byte[] InputStreamToByte(InputStream is) {
        try {
            ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
            int ch;
            while ((ch = is.read()) != -1) {
                bytestream.write(ch);
            }
            byte imgdata[] = bytestream.toByteArray();
            bytestream.close();
            return imgdata;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void Test(Context context) {
        Resources resources = MoviesApplication.getInstance().getResources();
        AssetManager am = resources.getAssets();
        try {
            String[] files = am.list("");
            for (String file : files) {
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static Uri getResourceUri(Context context, int res) {
        try {
            Context packageContext = context.createPackageContext(
                    context.getPackageName(), Context.CONTEXT_RESTRICTED);
            Resources resources = packageContext.getResources();

            Uri uri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://"
                    + resources.getResourcePackageName(res) + "/"
                    + resources.getResourceTypeName(res) + "/"
                    + resources.getResourceEntryName(res));

            // String appPkg = packageContext.getPackageName();
            // String resPkg = resources.getResourcePackageName(res);
            // String type = resources.getResourceTypeName(res);
            // String name = resources.getResourceEntryName(res);
            //
            //
            // Uri.Builder uriBuilder = new Uri.Builder();
            // uriBuilder.scheme(ContentResolver.SCHEME_ANDROID_RESOURCE);
            // uriBuilder.encodedAuthority(appPkg);
            // uriBuilder.appendEncodedPath(type);
            // if (!appPkg.equals(resPkg)) {
            // uriBuilder.appendEncodedPath(resPkg + ":" + name);
            // } else {
            // uriBuilder.appendEncodedPath(name);
            // }
            // return uriBuilder.build();
            return uri;

        } catch (Exception e) {
            return null;
        }
    }

    public static void saveFile(Bitmap bm, String fileName) {
        try {
            File dirFile = new File(ALBUM_PATH);
            if (!dirFile.exists()) {
                dirFile.mkdir();
            }
            File myCaptureFile = new File(ALBUM_PATH + fileName);
            BufferedOutputStream bos = new BufferedOutputStream(
                    new FileOutputStream(myCaptureFile));
            bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
            bos.flush();
            bos.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            bm.recycle();
        }
    }

    public static Bitmap getRes(Context context, String name) {
        ApplicationInfo appInfo = context.getApplicationInfo();
        int resID = context.getResources().getIdentifier(name, DRAWABLE,
                appInfo.packageName);
        return BitmapFactory.decodeResource(context.getResources(), resID);
    }

    /**
     * java去除字符串中的空格、回车、换行符、制表符
     *
     * @param str
     * @return zhangshuo 2014年6月18日 下午5:53:32
     */
    public static String replaceBlank(String str) {
        String dest = "";
        if (str != null) {
            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
            Matcher m = p.matcher(str);
            dest = m.replaceAll("");
        }
        return dest;
    }

    /**
     * Base64解码
     *
     * @param data
     * @return zhangshuo 2014年7月31日 下午6:20:57
     */
    public static String getBase64Decode(String data) {
        try {
            byte[] reuslt = Base64.decode(data, Base64.DEFAULT);
            return new String(reuslt);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static int getNumCores() {
        // Private Class to display only CPU devices in the directory listing
        class CpuFilter implements FileFilter {
            @Override
            public boolean accept(File pathname) {
                // Check if filename is "cpu", followed by a single digit number
                if (Pattern.matches("cpu[0-9]", pathname.getName())) {
                    return true;
                }
                return false;
            }
        }

        try {
            // Get directory containing CPU info
            File dir = new File("/sys/devices/system/cpu/");
            // Filter to only list the devices we care about
            File[] files = dir.listFiles(new CpuFilter());
            // Return the number of cores (virtual CPU devices)
            return files.length;
        } catch (Exception e) {
            // Print exception
            e.printStackTrace();
            // Default to return 1 core
            return 1;
        }
    }

    // 获取CPU最大频率
    // "/system/bin/cat" 命令行
    // "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq" 存储最大频率的文件的路径
    public static String getMaxCpuFreq() {
        if (!TextUtils.isEmpty(cpu_result) && !"N/A".equals(cpu_result)) {
            return cpu_result;
        } else {
            ProcessBuilder cmd;
            try {
                String[] args = {"/system/bin/cat",
                        "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq"};
                cmd = new ProcessBuilder(args);
                Process process = cmd.start();
                InputStream in = process.getInputStream();
                byte[] re = new byte[24];
                while (in.read(re) != -1) {
                    cpu_result = cpu_result + new String(re);
                }
                in.close();
            } catch (IOException ex) {
                ex.printStackTrace();
                cpu_result = "";
            }
            return cpu_result.trim();
        }
    }

    /**
     * 获取二级渠道
     *
     * @param context
     * @return
     */
    public static String getSubchannel(Context context) {
        ApplicationInfo appinfo = context.getApplicationInfo();
        String sourceDir = appinfo.sourceDir;
        String ret = "";
        ZipFile zipfile = null;
        try {
            zipfile = new ZipFile(sourceDir);
            Enumeration<?> entries = zipfile.entries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = ((ZipEntry) entries.nextElement());
                String entryName = entry.getName();
                if (entryName.contains("kuaikansubchannel")) {
                    ret = entryName;
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (zipfile != null) {
                try {
                    zipfile.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        String[] split = ret.split("_");
        if (split != null && split.length >= 2) {
            return split[split.length - 1];

        } else {
            return "";
        }
    }

    public static String getSignInfo() {
        try {
            PackageInfo packageInfo = MoviesApplication
                    .getInstance()
                    .getPackageManager()
                    .getPackageInfo(
                            MoviesApplication.getInstance().getPackageName(),
                            PackageManager.GET_SIGNATURES);
            Signature[] signs = packageInfo.signatures;
            Signature sign = signs[0];
            return parseSignature(sign.toByteArray());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "unknown";
    }

    private static String parseSignature(byte[] signature) {
        try {
            CertificateFactory certFactory = CertificateFactory
                    .getInstance("X.509");
            X509Certificate cert = (X509Certificate) certFactory
                    .generateCertificate(new ByteArrayInputStream(signature));
            return MD5Utils.md5(cert.getEncoded());
        } catch (CertificateException e) {
            e.printStackTrace();
        }
        return "unknown";
    }

    public static String getBrandName() {
        return android.os.Build.BRAND;
    }

    public static String getOSVersionName() {
        return android.os.Build.VERSION.RELEASE;
    }

    public static String getModel() {
        return android.os.Build.MODEL;
    }

    public static String getManufacturer() {
        return android.os.Build.MANUFACTURER;
    }

    @TargetApi(Build.VERSION_CODES.GINGERBREAD)
    public static String getSerialNumber() {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD) {
            return android.os.Build.SERIAL;
        }
        return "";
    }

    public static String getDate(String dateStr, String format){
        String dateString = "";
        if(!TextUtils.isEmpty(dateStr) && !TextUtils.isEmpty(format)){
            try {
                DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
                Date date = format1.parse(dateStr);
                SimpleDateFormat format2 = new SimpleDateFormat(format);
                dateString = format2.format(date);

            } catch (Exception e) {
                e.printStackTrace();
                DateFormat format1 = new SimpleDateFormat("yyyy");
                Date date = null;
                try {
                    date = format1.parse(dateStr);
                } catch (ParseException e1) {
                    e1.printStackTrace();
                }
                SimpleDateFormat format2 = new SimpleDateFormat(format);
                dateString = format2.format(date);
            }
        }

        return dateString;
    }
    public static String getCurrentTimeByPattern(String pattern) {
        DateFormat df = new SimpleDateFormat(pattern, Locale.US);
        String currentTime = df.format(new Date());
        return currentTime;
    }

    public static String getTodayTime() {
        try {
            if (TextUtils.isEmpty(todayTime)) {
                long time = System.currentTimeMillis();
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                Date date = new Date(time);
                todayTime = format.format(date);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return todayTime;
    }

    public static Bitmap netUrlToBitMap(String netUrl) {
        Bitmap bitmap = null;
        InputStream in = null;
        try {
            if (!TextUtils.isEmpty(netUrl)) {
                URL url = new URL(netUrl);
                URLConnection conn = url.openConnection();
                conn.connect();
                in = conn.getInputStream();
                BufferedInputStream bis = new BufferedInputStream(in);
                bitmap = BitmapFactory.decodeStream(bis);
            }
        } catch (Exception e) {
            if (null != e) {
                e.printStackTrace();
            }
        }
        return bitmap;
    }

    public static void AES256_Encode(byte[] Key) {
        try {
            // 初始化SecretKeySpec对象
            SecretKeySpec skeySpec = new SecretKeySpec(Key, "AES");
            // 初始化Cipher对象
            Cipher cipher = Cipher.getInstance("AES");
            // 用指定密匙对象初始化加密Cipher对象
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            byte[] result = cipher.doFinal();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static byte[] AES256_Encode(String str) {
        try {
            // // 获取KeyGenerator对象
            // KeyGenerator kgen = KeyGenerator.getInstance("AES");
            // // 设置加密密匙位数，目前支持128、192、256位
            // kgen.init(keySize);
            // // 获取密匙对象
            // SecretKey skey = kgen.generateKey();
            // // 获取随机密匙
            // byte[] raw = skey.getEncoded();
            // 初始化SecretKeySpec对象
            SecretKeySpec skeySpec = new SecretKeySpec(AES_KEY, "AES");
            // 初始化Cipher对象
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            // 用指定密匙对象初始化加密Cipher对象
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            // 加密字符串
            return cipher.doFinal(str.getBytes("utf-8"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String AES256_decode(byte[] base64plain, byte[] aesKey) {
        try {
            Cipher c = Cipher.getInstance("AES/ECB/PKCS5Padding");
            SecretKeySpec k = new SecretKeySpec(aesKey, "AES");
            byte[] byteContent = base64plain;
            c.init(Cipher.DECRYPT_MODE, k);
            byte[] result = c.doFinal(byteContent);
            return new String(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 设置公网ip
     *
     * @return
     */
    public static void setPublicIpAddress(String ip) {
        publicIpAddress = ip;
    }

    /**
     * 获取公网ip
     *
     * @return
     */
    public static String getPublicIpAddress() {
        return publicIpAddress;
    }


    /**
     * 获取ip
     *
     * @return
     */
    public static String getLocalIpAddress() {
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface
                    .getNetworkInterfaces(); en.hasMoreElements(); ) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf
                        .getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress() && !inetAddress.isLinkLocalAddress()) {
                        return inetAddress.getHostAddress().toString();
                    }
                }
            }
        } catch (SocketException ex) {
            ex.printStackTrace();
        }
        return null;
    }

    public static void jumpOnePointWebViewActivity(Context context, String adUrl, String name) {
        Intent intent = new Intent();
        Context mContext = context;
        if (mContext == null) {
            mContext = MoviesApplication.getInstance();
        }
        JumpData jumpData = new JumpData();
        Bundle jumpbundle = new Bundle();
        jumpData.setPlayUrl(adUrl);
        jumpData.setName(name);
        intent.setClass(mContext, CommonWebViewActivity.class);
        jumpbundle.putSerializable(Utils.CHANNEL_DTAT, jumpData);
        jumpbundle.putString("fromTag","onePiontSource");
        intent.putExtras(jumpbundle);
        intent.putExtra(MoviesApplication.START_FROM_NOTIFICATION, false);
        if (!(mContext instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        mContext.startActivity(intent);
    }
    public static void jumpWebViewActivity(Context context, String adUrl, String name) {
        jumpWebViewActivity(context, adUrl, name, false);
    }

    /**
     * 应用内广告点击跳转webview
     *
     * @param context
     * @param adUrl
     */
    public static void jumpWebViewActivity(Context context, String adUrl, String name, boolean isfrompush) {
        Intent intent = new Intent();
        Context mContext = context;
        if (mContext == null) {
            mContext = MoviesApplication.getInstance();
        }
        JumpData jumpData = new JumpData();
        Bundle jumpbundle = new Bundle();
        // 当前是跳转链接
        LogUtils.e(CommonWebViewActivity.TAG, "jumpWebViewActivity method called and adURL is " + adUrl);
        jumpData.setPlayUrl(adUrl);
        jumpData.setName(name);
        intent.setClass(mContext, CommonWebViewActivity.class);
        jumpbundle.putSerializable(Utils.CHANNEL_DTAT, jumpData);
        intent.putExtras(jumpbundle);
        intent.putExtra(MoviesApplication.START_FROM_NOTIFICATION, isfrompush);
        if (!(mContext instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        mContext.startActivity(intent);
    }

    /**
     * 输出js截流日志
     *
     * @param mContext
     * @param fileName
     * @param log
     */
    public synchronized static void writeJsSniffLogData(Context mContext, String fileName, String log) {
        if (!LogUtils.DEBUG)
            return;
        FileOutputStream fileOutputStream = null;
        PrintStream printStream = null;
        LogUtils.e(TAG, " jslog !!!!!!!!!!" + fileName + "!!!!!!!!!!!file save local ! ");
        try {
            fileOutputStream = mContext.openFileOutput(fileName, mContext.MODE_PRIVATE);
            printStream = new PrintStream(fileOutputStream);
            printStream.println(HEADER);
            printStream.println(log);
            printStream.println(FOOTER);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != printStream)
                    printStream.close();
                if (null != fileOutputStream)
                    fileOutputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 工具类 输出日志
     *
     * @param mContext
     * @param fileName
     * @param log
     */
    public static void writeLogFile(Context mContext, String fileName, String log) {
        if (!LogUtils.DEBUG)
            return;
        FileOutputStream fileOutputStream = null;
        PrintStream printStream = null;
        LogUtils.e("wym", " log !!!!!!!!!!" + fileName + "!!!!!!!!!!!file save local ! ");
        try {
            fileOutputStream = mContext.openFileOutput(fileName, mContext.MODE_PRIVATE);
            printStream = new PrintStream(fileOutputStream);
            printStream.println(log);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != printStream)
                    printStream.close();
                if (null != fileOutputStream)
                    fileOutputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 按照指定分隔符将list转为str
     *
     * @param list
     * @param separator
     * @return
     */
    public static String convertListToStr(List<String> list, String separator) {
        String result = "";
        if (null == list || list.isEmpty())
            return result;
        int size = list.size();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < size; i++) {
            if (i != size - 1)
                sb.append(list.get(i)).append(separator);
            else
                sb.append(list.get(i));
        }
        result = sb.toString();
        return result;
    }

    /**
     * 生成随机数字，数字字符串
     *
     * @param passLength 长度
     * @param type       0 数字字符串
     * @return
     */
    public static String genRandomCode(int passLength, int type) {
        StringBuffer buffer = null;
        StringBuffer sb = new StringBuffer();
        Random r = new Random();
        r.setSeed(new Date().getTime());
        switch (type) {
            case 0:
                buffer = new StringBuffer("0123456789");
                break;
            case 1:
                buffer = new StringBuffer("abcdefghijklmnopqrstuvwxyz");
                break;
            case 2:
                buffer = new StringBuffer("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
                break;
            case 3:
                buffer = new StringBuffer(
                        "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");
                break;
            case 4:
                buffer = new StringBuffer(
                        "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
                sb.append(buffer.charAt(r.nextInt(buffer.length() - 10)));
                passLength -= 1;
                break;
            case 5:
                String s = UUID.randomUUID().toString();
                sb.append(s.substring(0, 8) + s.substring(9, 13)
                        + s.substring(14, 18) + s.substring(19, 23)
                        + s.substring(24));
        }

        if (type != 5) {
            int range = buffer.length();
            for (int i = 0; i < passLength; ++i) {
                sb.append(buffer.charAt(r.nextInt(range)));
            }
        }
        return sb.toString();
    }

    /**
     * 根据男或者女得到对应的编码。0---男，1---女，2---保密,qq的
     * @param gender
     * @return
     */
    public static String getQQGender(String gender){
        String sex = "2";
        if("男".equals(gender)){
            sex = "0";
        }else if("女".equals(gender)){
            sex = "1";
        }else{
            sex = "2";
        }
        return sex;
    }

    /**
     * 根据男或者女得到对应的编码。0---男，1---女，2---保密,微博的
     * @param gender
     * @return
     */
    public static String getWeiboGender(String gender){
        String sex = "2";
        if("1".equals(gender)){
            sex = "0";
        }else if("0".equals(gender)){
            sex = "1";
        }else{
            sex = "2";
        }
        return sex;
    }

    public static PostCloudErrorBean genetateCloudErrorData() {

        PostCloudErrorBean postCloudErrorBean = new PostCloudErrorBean();
        PlatForm platForm = new PlatForm();
        platForm.setHardware(MoviesUtils.getDeviceModel() + " phone");
        platForm.setSys("Android " + MoviesUtils.getOSVersion());
        platForm.setIp(PreferencesManager.getInstance().getPublicIp());
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        platForm.setDate(formatter.format(curDate));
        postCloudErrorBean.setPlatForm(platForm);
        App app = new App();
        app.setName(MoviesApplication.getInstance().getString(R.string.app_name));
        app.setVer(MoviesUtils.getClientVersionName());
        postCloudErrorBean.setApp(app);
        User user = new User();
        user.setType("anonymous");
        user.setLocation(SharePreferenceManager.getVaule(MoviesApplication.getInstance(),
                MyLocationManager.LOCATIONKEY, ""));
        postCloudErrorBean.setUser(user);
        postCloudErrorBean.setResource(new Resource());
        Cde cde = new Cde();
        CDEManager cdeManager = CDEManager.getInstance(MoviesApplication.getInstance());
        cde.setVer(cdeManager.getmCdeHelper().getServiceVersion());
        postCloudErrorBean.setCde(cde);
        return postCloudErrorBean;
    }


    public static boolean isBackground(Context context) {
        ActivityManager activityManager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager
                .getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo appProcess: appProcesses) {
            if (appProcess.processName.equals(context.getPackageName())) {
                if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND) {
                    LogUtils.i("后台", appProcess.processName);
                    return true;
                } else {
                    LogUtils.e("前台", appProcess.processName);
                    return false;
                }
            }
        }
        return false;
    }

    public static boolean isAppOnForeground(Context context) {
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        String packageName = context.getPackageName();

        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager
                .getRunningAppProcesses();
        if (appProcesses == null)
            return false;

        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
            if (appProcess.processName.equals(packageName)
                    && appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                return true;
            }
        }
        return false;
    }

    public static boolean isSimulator() {
        String text = "";
        try {
            FileReader fr = new FileReader("/proc/cpuinfo");
            BufferedReader br = new BufferedReader(fr);

            StringBuilder sb = new StringBuilder("");
            String line;
            try {
                while ((line = br.readLine()) != null) {
                    sb.append(line);
                    sb.append("\n");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

            text = sb.toString();
            if(!TextUtils.isEmpty(text)){
                text = text.toLowerCase();
                if(text.contains("intel")){
                    if(!text.contains("atom")){
                        return true;
                    }
                }else{
                    if(!text.contains("arm") && !text.contains("aarch")){
                        return true;
                    }
                }
            }
            fr.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        boolean contain_mmcblk = false;
        try {
            FileReader frd = new FileReader("/proc/diskstats");
            BufferedReader brd = new BufferedReader(frd);
            while ((text = brd.readLine()) != null){
                if(text.contains("mmcblk") || text.contains("dm")){
                    contain_mmcblk = true;
                    break;
                }
            }
            frd.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if(!contain_mmcblk){
            return true;
        }

        String manufacturer = android.os.Build.MANUFACTURER;
        if("XXAndroid".equals(manufacturer)){   //猩猩模拟器
            return true;
        }

        return false;
    }

    public static boolean isMonkeyRunning() {
        return ActivityManager.isUserAMonkey();
    }

    public static boolean isAppInstalled(Context context, String appName) {
        return context.getPackageManager().getLaunchIntentForPackage(appName)!= null;
    }

    public static boolean deviceCanHandleIntent(final Context context, final Intent intent) {
        try {
            final PackageManager packageManager = context.getPackageManager();

            final List<ResolveInfo> activities = packageManager.queryIntentActivities(intent, 0);
            return !activities.isEmpty();
        } catch (NullPointerException e) {
            return false;
        }
    }

    public static boolean isRooted() {
        // get from build info, test build rom
        String buildTags = android.os.Build.TAGS;
        if (buildTags != null && buildTags.contains("test-keys")) {
            return true;
        }

        boolean isRooted = false;
        String isRootString = SharePreferenceManager.getVaule(MoviesApplication.getInstance(), SharePreferenceManager.ISROOTED, "2");
        if("2".equals(isRootString)){
            // try executing commands
            isRooted = canExecuteCommand("/system/xbin/which su")
                    || canExecuteCommand("/system/bin/which su") || canExecuteCommand("which su")
                    || canExecuteCommand("busybox which su");
            SharePreferenceManager.saveVaule(MoviesApplication.getInstance(), SharePreferenceManager.ISROOTED, isRooted?"1":"0");
        }else if("1".equals(isRootString)){
            isRooted = true;
        }else if("0".equals(isRootString)){
            isRooted = false;
        }
        return isRooted;
    }

    // executes a command on the system
    private static boolean canExecuteCommand(String command) {
        Process process = null;
        try {
            process = Runtime.getRuntime().exec(command);
            BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String info = in.readLine();
            if (info != null) return true;
            return false;
        } catch (Exception e) {
            //do noting
        } finally {
            if (process != null) process.destroy();
        }
        return false;
    }

    //判断是否横屏
    public static boolean isOrientionLandscape(Context context) {
        Configuration mConfig = context.getResources().getConfiguration();
        if(Configuration.ORIENTATION_LANDSCAPE == mConfig.orientation){
            return true;
        }else{
            return false;
        }
    }

    //获取系统浏览器ua
    public static String getBrowserUa(Context context) {
        String ua = SharePreferenceManager.getVaule(MoviesApplication.getInstance(), SharePreferenceManager.BROWSER_UA, "");
        if(TextUtils.isEmpty(ua)){
            ua = new WebView(context).getSettings().getUserAgentString();
            SharePreferenceManager.saveVaule(MoviesApplication.getInstance(), SharePreferenceManager.BROWSER_UA, ua);
        }
        return ua;
    }

}
